/**
 * Copyright (c) 2018 小润科技 All rights reserved.

 * 版权所有，侵权必究！
 */

package com.xr.sy.modules.security.service.impl;

import com.xr.common.constant.Constant;
import com.xr.common.service.impl.BaseServiceImpl;
import com.xr.common.utils.Result;
import com.xr.sy.modules.security.dao.SysUserTokenDao;
import com.xr.sy.modules.security.entity.SysUserTokenEntity;
import com.xr.sy.modules.security.oauth2.TokenGenerator;
import com.xr.sy.modules.security.service.SysUserTokenService;
import com.xr.sy.modules.sys.dto.SysUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
	/**
	 * 12小时后过期
	 */
	private final static int EXPIRE = 3600 * 12;

	@Autowired
	RedisTemplate redisTemplate;

	@Override
	public Result createToken(SysUserDTO user) {
		String token = TokenGenerator.generateValue();
		redisTemplate.boundValueOps(token).set(user, EXPIRE, TimeUnit.SECONDS);
		Map<String, Object> map = new HashMap<>(2);
		map.put(Constant.TOKEN_HEADER, token);
		map.put("expire", EXPIRE);
		map.put("username", user.getEmail());
		return new Result().ok(map);
	}

	@Override
	public void logout(Long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//修改token
		baseDao.updateToken(userId, token);
	}
}